package mf.trees;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/** Represents a straight-line context-free tree grammar. */
public class SLTreeGrammar {
	
	//list of rules
	private ArrayList<Rule> rules = new ArrayList<Rule>();
	
	/** Constructs a blank grammar. */
	public SLTreeGrammar() {}
	
	/** Construct a new grammar defined by file <i>f</i>. */
	public SLTreeGrammar(File f) {
		try {
			BufferedReader br = new BufferedReader(new FileReader(f));
			String in;
			
			//read grammar file, but ignore blank lines and lines starting with //
			while((in = br.readLine()) != null) {
				if(in.startsWith("//") || in.length() == 0)
					rules.add(new Rule(null));
				
				//process lines
				rules.add(new Rule(in.split(",")));
			}
		} catch (IOException e) {
			System.out.println("File " + f + " not found. Quitting..");
			System.exit(0);
		}
	}

	/** Print a human-readable form of the grammar. */
	public String toString() {
		String ret = "";//The grammar has the following rules\n";
				
		for(int i=0; i<rules.size(); i++) {
			Rule r = rules.get(i);
			
			ret += "A_" + i + (r.hasParameter() ? "(x)" : "") + "\t->\t" +
					rules.get(i).toString() + "\n";
		}
		
		return ret;
	}
	
	/** Return the number of rules of the grammar. */
	public int size() {
		return rules.size();
	}

	/** Get the rule for non-terminal A_i. */
	public Rule getRule(int i) {
		return rules.get(i);
	}
}